package com.warrior.superdata.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.warrior.superdata.constants.CommonConstant;
import com.warrior.superdata.enums.OperateType;
import com.warrior.superdata.mysql.entity.dto.ApiParamDto;
import com.warrior.superdata.service.InsertSqlService;
import com.warrior.superdata.dds.DataSourceHelp;
import com.warrior.superdata.enums.DatasourceType;
import com.warrior.superdata.mysql.entity.dto.ApiInfoDetailDto;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @ClassName: EsInsertServiceImpl.java
 * @date: 2022/3/10 18:13
 * @author xujian
 */
@Service
@Slf4j
public class EsInsertServiceImpl implements InsertSqlService {

    @Override
    public String getDatasourceType() {
        return DatasourceType.ES.getName();
    }

    @Override
    public String getOperateType() {
        return OperateType.INSERT.getName();
    }

    @Autowired
    private DataSourceHelp dataSourceHelp;

    @Override
    public Object execute(ApiInfoDetailDto apiInfoDetailDto) {
        Integer result = 0;
        List<ApiParamDto> params = apiInfoDetailDto.getParams();
        String[] fieldValue = params.get(0).getParamValue().toString().split(CommonConstant.FIELD_VALUE_SPLICE_LIST);
        BulkRequest request = new BulkRequest();
        for (int i = 0; i < fieldValue.length; i++) {
            JSONObject jsonObject = new JSONObject();
            for (ApiParamDto param : params) {
                String[] split = param.getParamValue().toString().split(CommonConstant.FIELD_VALUE_SPLICE_LIST);
                jsonObject.put(param.getParamTableFieldName().split("\\.")[1], split[i]);
            }
            IndexRequest indexRequest = new IndexRequest(apiInfoDetailDto.getMainTableName(), CommonConstant.ES_DOC).source(jsonObject, XContentType.JSON);
            request.add(indexRequest);
        }

        try {
            RestHighLevelClient restHighLevelClient = dataSourceHelp.getRestHighLevelClient(apiInfoDetailDto.getDatasourceDto());
            BulkResponse bulk = restHighLevelClient.bulk(request);
            result = bulk.getItems() == null ? 0 : bulk.getItems().length;
        } catch (Exception e) {
            log.error("es insert异常 errMsg:{}", e.getMessage());
        }
        return result;
    }
}
